package com.darryring.libcore.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 */
public class StringUtil {

    /**
     * 检测字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isNotNull(String str) {
        boolean result = false;
        if (str != null && !str.equals("") && !"null".equals(str)
                && str.trim().length() > 0) {
            result = true;
        }
        return result;
    }

    public static boolean isNull(String str) {
        if (str == null || "".equals(str) || " ".equals(str)
                || "null".equals(str) || "NULL".equals(str)) {
            return true;
        } else {
            return false;
        }
    }

    public static String trim(String str) {
        if (str != null) {
            str = str.trim().replaceAll("\\s", "");
        }
        return str;
    }

    public static String strToUpper(String str) {
        String result = null;
        if (str != null && !str.equals("") && !"null".equals(str)) {
            result = str.toUpperCase();
        }
        return result;
    }

    /**
     * 获得id加逗号 的id字符串.
     *
     * @param idsStr
     * @return
     */
    public static String getIdsStr(String idsStr) {
        if (idsStr.endsWith(",")) {
            idsStr = idsStr.substring(0, idsStr.length() - 1);
        } else if (isNull(idsStr)) {
            idsStr = "0";
        }
        return idsStr;
    }


    public static String getEncodeGB2312AsStr(String str) {
        String resultStr = "";
        try {
            if (isNotNull(str)) {
                resultStr = URLEncoder.encode(str, "gb2312");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return resultStr;
    }

    /**
     * @param in
     * @return
     * @description 根据InputStream得到返回的结果字符串
     * @version 1.0
     * @author 吕振威
     * @date 2012-3-28 下午2:51:58
     * @update 2012-3-28 下午2:51:58
     */
    public static String convertStreamToString(InputStream in) {

        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }


    /**
     * @param str
     * @return
     * @description 将字符串转为InputStream
     * @version 1.0
     * @author 吕振威
     * @date 2012-3-28 下午4:02:20
     * @update 2012-3-28 下午4:02:20
     */
    public static InputStream convertStrToInputStream(String str) {
        ByteArrayInputStream stream = null;
        if (str != null && str.length() > 0) {
            stream = new ByteArrayInputStream(str.getBytes());
        }
        return stream;
    }

    /**
     * @param str
     * @return
     * @description 字符串转换为utf-8编码
     */
    public static String getEncodeUTF8AsStr(String str) {
        String resultStr = "";
        try {
            if (isNotNull(str)) {
                resultStr = URLEncoder.encode(str, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return resultStr;
    }

    /**
     * @param str
     * @return
     * @description 去除换行符
     */
    public static String removeNewLineSymbol(String str) {
        if (isNotNull(str)) {
            if (str.endsWith("\n")) {
                str = str.substring(0, str.length() - 1);
            }
        }
        return str;
    }

    @SuppressWarnings("unused")
    public static boolean judgeHasChinese(String content) {
        int chinese = 0;
        int english = 0;
        boolean isChinese = false;

        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < content.length(); i++) {
            String retContent = content.substring(i, i + 1);
            // 生成一个Pattern,同时编译一个正则表达式
            boolean isChina = retContent.matches("[\u4E00-\u9FA5]");
            if (isChina) {
                chinese++;
            }

            boolean isCapital = retContent.matches("[A-Z]");
            if (isCapital) {
                english++;
            }
            boolean isNum = retContent.matches("[0-9]");
            if (isNum) {
                english++;
            }
        }
        if (chinese > 0) {
            isChinese = true;
        } else {
            isChinese = false;
        }

        return isChinese;
    }

    public static void propertyCopy(Object from, Object to) {
        Field[] fields = from.getClass().getFields();
        for (int i = 0; i < fields.length; i++) {
            String name = fields[i].getName();
            Field field;
            try {
                field = to.getClass().getField(name);
                field.set(to, fields[i].get(from));
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
    }

    public static String Md5(String str) {
        if (str != null && !str.equals("")) {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                        '9', 'a', 'b', 'c', 'd', 'e', 'f'};
                byte[] md5Byte = md5.digest(str.getBytes("UTF8"));
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < md5Byte.length; i++) {
                    sb.append(HEX[(int) (md5Byte[i] & 0xff) / 16]);
                    sb.append(HEX[(int) (md5Byte[i] & 0xff) % 16]);
                }
                str = sb.toString();
            } catch (NoSuchAlgorithmException e) {
            } catch (Exception e) {
            }
        }
        return str;
    }

    // Empty checks
    //-----------------------------------------------------------------------
    /**
     * <p>Checks if a CharSequence is empty ("") or null.</p>
     *
     * <pre>
     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * </pre>
     *
     * <p>NOTE: This method changed in Lang version 2.0.
     * It no longer trims the CharSequence.
     * That functionality is available in isBlank().</p>
     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is empty or null
     * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence)
     */
    public static boolean isEmpty(final CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * <p>Checks if a CharSequence is not empty ("") and not null.</p>
     *
     * <pre>
     * StringUtils.isNotEmpty(null)      = false
     * StringUtils.isNotEmpty("")        = false
     * StringUtils.isNotEmpty(" ")       = true
     * StringUtils.isNotEmpty("bob")     = true
     * StringUtils.isNotEmpty("  bob  ") = true
     * </pre>
     *
     * @param cs  the CharSequence to check, may be null
     * @return {@code true} if the CharSequence is not empty and not null
     * @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence)
     */
    public static boolean isNotEmpty(final CharSequence cs) {
        return !isEmpty(cs);
    }

    // Equals
    //-----------------------------------------------------------------------
    /**
     * <p>Compares two CharSequences, returning {@code true} if they represent
     * equal sequences of characters.</p>
     *
     * <p>{@code null}s are handled without exceptions. Two {@code null}
     * references are considered to be equal. The comparison is case sensitive.</p>
     *
     * <pre>
     * StringUtils.equals(null, null)   = true
     * StringUtils.equals(null, "abc")  = false
     * StringUtils.equals("abc", null)  = false
     * StringUtils.equals("abc", "abc") = true
     * StringUtils.equals("abc", "ABC") = false
     * </pre>
     *
     * @see Object#equals(Object)
     * @param cs1  the first CharSequence, may be {@code null}
     * @param cs2  the second CharSequence, may be {@code null}
     * @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null}
     * @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
     */
    public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
        if (cs1 == cs2) {
            return true;
        }
        if (cs1 == null || cs2 == null) {
            return false;
        }
        if (cs1 instanceof String && cs2 instanceof String) {
            return cs1.equals(cs2);
        }
        return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));
    }

    // Contains
    //-----------------------------------------------------------------------
    /**
     * <p>Checks if CharSequence contains a search character, handling {@code null}.
     * This method uses {@link String#indexOf(int)} if possible.</p>
     *
     * <p>A {@code null} or empty ("") CharSequence will return {@code false}.</p>
     *
     * <pre>
     * StringUtils.contains(null, *)    = false
     * StringUtils.contains("", *)      = false
     * StringUtils.contains("abc", 'a') = true
     * StringUtils.contains("abc", 'z') = false
     * </pre>
     *
     * @param seq  the CharSequence to check, may be null
     * @param searchChar  the character to find
     * @return true if the CharSequence contains the search character,
     *  false if not or {@code null} string input
     * @since 2.0
     * @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int)
     */
    public static boolean contains(final CharSequence seq, final int searchChar) {
        if (isEmpty(seq)) {
            return false;
        }
        return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0;
    }

    /**
     * <p>Checks if CharSequence contains a search CharSequence, handling {@code null}.
     * This method uses {@link String#indexOf(String)} if possible.</p>
     *
     * <p>A {@code null} CharSequence will return {@code false}.</p>
     *
     * <pre>
     * StringUtils.contains(null, *)     = false
     * StringUtils.contains(*, null)     = false
     * StringUtils.contains("", "")      = true
     * StringUtils.contains("abc", "")   = true
     * StringUtils.contains("abc", "a")  = true
     * StringUtils.contains("abc", "z")  = false
     * </pre>
     *
     * @param seq  the CharSequence to check, may be null
     * @param searchSeq  the CharSequence to find, may be null
     * @return true if the CharSequence contains the search CharSequence,
     *  false if not or {@code null} string input
     * @since 2.0
     * @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence)
     */
    public static boolean contains(final CharSequence seq, final CharSequence searchSeq) {
        if (seq == null || searchSeq == null) {
            return false;
        }
        return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0;
    }

}
